# -*- coding:UTF-8 -*-
import requests
import pytest
import json
import os
import time
import logging
import config as config
import convertTo as convertTo
import sys
sys.path.append("..")
import utils.request_xl as request_xl


class requestApi(object):
    def __init__(self, caseFileName, sheetName, ApiPurpose,source):
        self.caseFileName = caseFileName
        self.sheetname = sheetName
        self.ApiPurpose = ApiPurpose
        self.source = source
        # 获取文件路径
        self.filePath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # print(filePath)
        self.confPath = self.filePath + "/data/conf.ini"
        self.cr = config.ConfigReader(self.confPath)
        # 读取case配置文件并获得对应值
        rxl = request_xl.request_xl(caseFileName)
        self.api_values = rxl.get_xl(sheetName, ApiPurpose)


    # 请求时间写入配置文件
    def r_time(self):
        rtime = str(int(time.time()))
        self.cr.set(self.source, 'requestTime', rtime)
        self.rTime = self.cr.get(self.source, 'requestTime')
        # print("=======request time ======%s" % self.rTime)
        return self.rTime


    # 请求头
    def headers(self):
        os = self.cr.get(self.source, 'os')
        osVersion = self.cr.get(self.source, 'osVersion')
        appVersion = self.cr.get(self.source, 'appVersion')
        apiVersion = self.cr.get(self.source, 'apiVersion')
        userId = self.cr.get(self.source, 'userId')
        requestTime = self.r_time()
        # print("====requestTime=====%s" % requestTime)
        deviceCode = self.cr.get(self.source, 'deviceCode')
        type = self.cr.get(self.source, 'type')
        self.t_headers = {
            'cli-os': os,
            'cli-os-version': osVersion,
            'app-version': appVersion,
            'api-version': apiVersion,
            'request-Time': requestTime,
            'cli-type': type,
            'deviceCode': deviceCode,
            'cli-id': userId,
            'Content-Type': 'application/json; charset=utf-8'
        }
        return self.t_headers


    # 请求参数按照首字母顺序排列并组合
    def sortParam(self):
        # 将请求参数按照首字母顺序排列
        self.paramStr = eval(self.api_values[6])
        # 去掉字符串中的所有空格
        self.paramStr = self.paramStr.replace(" ", "")
        dic = sorted(self.paramStr.items(), key=lambda x: x[0])
        # print("dic======%s" % dic)
        parameterDic = dict(dic)
        parametersNew = []
        # print(parameterDic.keys())
        # 将请求参数按照key = value & key = value组合
        for i in parameterDic.keys():
            parameterValue = parameterDic[i]
            # print(parameterValue)
            parameterNew = "\"%s\":\"%s\"" % (i, parameterValue)
            # print("========parameterNew====%s" %parameterNew)
            parametersNew.append(parameterNew)
            # print("--------parameterNew-----%s" % parameterNew)
        self.newParam = ",".join(str(i) for i in parametersNew)
        self.newParam = "{%s}" % self.newParam
        print(self.newParam)
        return self.newParam

    # 生成安卓签名
    def androidSignature(self):
        s = requestApi(self.caseFileName, self.sheetname, self.ApiPurpose, self.source)
        self.API_Host = self.api_values[2]
        self.Request_URL = self.api_values[3]
        url = self.API_Host + self.Request_URL
        paramStr1 = s.sortParam()
        apiVersion = self.cr.get(self.source, 'apiVersion')
        appVersion = self.cr.get(self.source, "appVersion")
        token = self.cr.get(self.source, "token")
        # deviceCode = self.cr.get('self.source', 'deviceCode')
        deviceCode = ''
        userId = self.cr.get(self.source, 'userId')
        r_time = s.r_time()
        signatureStr = "=" + token + " " + "[" + " " + ";" + apiVersion + " " + "<" + userId + "_" + " " + "%" + " " + r_time + "*" + " " + "!" + appVersion + "……" + url + " " + "+" + paramStr1 + " " + "]" + "-" + deviceCode + "6"
        # print(signatureStr)
        # 将组合的签名字符串进行MD5加密
        ct = convertTo.Convert(signatureStr)
        self.androidSign = ct.convertMD5()
        print(self.androidSign)
        return self.androidSign

    # 生成ios签名
    def iosSignature(self):
        s = requestApi(self.caseFileName, self.sheetname, self.ApiPurpose, self.source)
        # url = self.cr.get('Andorid_Basic', 'url')
        self.API_Host = self.api_values[2]
        self.Request_URL = self.api_values[3]
        t_url = self.API_Host + self.Request_URL
        paramStr1 = s.sortParam()
        apiVersion = self.cr.get(self.source, 'apiversion')
        appVersion = self.cr.get(self.source, "appversion")
        token = self.cr.get(self.source, "token")
        deviceCode = self.cr.get(self.source, 'deviceCode')
        # deviceCode = ''
        userId = self.cr.get(self.source, 'userId')
        r_time = s.r_time()
        signatureStr = paramStr1 + " " + "%" + t_url + " " + "|" + apiVersion + " " + "?" + deviceCode + "}" + appVersion + " " + "%" + r_time + " "  + userId + "[" + token
        print("====signatureStr=====%s" % signatureStr)
        # 将组合的签名字符串进行MD5加密
        ct = convertTo.Convert()
        self.iosSign = ct.convertMD5(signatureStr)
        print(self.iosSign)
        return self.iosSign


    # 请求接口
    def execute(self):
        try:
            self.API_Host = self.api_values[2]
            self.Request_URL = self.api_values[3]
            self.Request_Method = self.api_values[4]
            # data = api_values[6]
            # self.Request_Data = eval(api_values[6])
            self.Request_Data = str(self.api_values[6])
            s = requestApi(self.caseFileName, self.sheetname, self.ApiPurpose, self.source)
            if self.source == "andorid":
                signatureStr = s.androidSignature()
            if self.source == "ios":
                signatureStr = s.iosSignature()
            # self.Encryption = api_values[7]
            # 检查结果点
            # self.CheckPoint = api_values[8]
            url ="http://" + self.API_Host + self.Request_URL + "?signature=" + signatureStr
            # print(url)
            t_headers = self.headers()
            print(t_headers)
            print("=======request data =====%s" % self.Request_Data)
            response = requests.request(self.Request_Method, url, headers=t_headers, data=self.Request_Data)
            # 直接返回json
            # return response.text
            logging.info(response.text)
            logging.info("request API end")
            api_result = json.loads(response.text)
            print(api_result)
            return api_result
        except Exception as e:
            logging.info("===== request API error =====%s" % e)
            pytest.fail("CASE FAIL")
            return 0


# 测试数据
API = requestApi("Test_API_CASE.xlsx", "login_register", "add_friend_ture","ios")
API.execute()
# API = requestApi("Test_API_CASE.xlsx", "friends", "get_friendlist","ios")
# API.execute()